//
//  SelectList.m
//  Trading365
//
//  Created by yifei tong on 12-2-8.
//  Copyright (c) 2012年 dhc. All rights reserved.
//

#import "QuotSelectList.h"
#import "TaskManager.h"
#import "XmlRpc.h"
#import "Session.h"
#import "InfoType.h"


@implementation QuotSelectList
@synthesize table;
@synthesize list;
@synthesize lastIndexPath;
@synthesize selectProductArray;
@synthesize selectBeginBlcok;
@synthesize row,section;
@synthesize customerID,productID;
@synthesize lastSelectID;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)init
{
	self = [super init];
	if(self)
	{
        responseParams = [[NSMutableArray alloc] initWithCapacity:0];
        indexpathDic = [[NSMutableDictionary alloc] initWithCapacity:0];
	}
	
	return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [lastSelectID release];
    [table release];
//    [search release];
    [list release];
    [lastIndexPath release];
    [selectProductArray release];
    [customerID release];
    [productID release];
    [super dealloc];
}

- (void)initSelectBeginBlcok:(SelectBeginBlcok)selectBeginBlcok1
{
    self.selectBeginBlcok=selectBeginBlcok1;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [self init];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.search.showsCancelButton=NO;
    
//    UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
//                                   initWithTitle:@"返回" 
//                                   style:UIBarButtonItemStyleDone
//                                   target:self
//                                   action:@selector(goBack:)];
//    self.navigationItem.leftBarButtonItem = saveButton;
//    [saveButton release];
        
    [self refreshData];
    [self.table reloadData];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    table=nil;
    search = nil;
    
    [[[TaskManager Share] GetTaskByType:GetQuotSelectList Delegate:self] cancel];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Table view data source

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [responseParams count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                       reuseIdentifier: CellIdentifier] autorelease];
    }
    if (indexPath.row>[responseParams count]) {
        return cell;
    }
    
    NSUInteger row1 = [indexPath row];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:18];
    
    NSMutableDictionary *tmp_dictionary = nil;
    if (row1 < [responseParams count])
    {
        tmp_dictionary = [[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:row1]];
    }else
    {
       tmp_dictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    }

    //1产品类别
    if (infotype == INFO_TYPE_PRODUCT_CATEGORY) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"product_category_name"];        
    }

    //2@"单位",
    if (infotype == INFO_TYPE_PRODUCT_UNIT) {
        cell.textLabel.text =[tmp_dictionary objectForKey:@"unit_name_cn"];        
    }

    //3@"海关编码",
    if (infotype == INFO_TYPE_PRODUCT_CUSTOM_CODE) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"customs_prod_name_cn"];        
    }
   
    //4@"客户",
    if (infotype == INFO_TYPE_CUSTOMER) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"customer_name_cn"];        
    }
    
    //5产品
    if (infotype == INFO_TYPE_PRODUCT) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"product_name_ch"];        
    }
    
    //6@"业务员",
    if (infotype == INFO_TYPE_EMPLOYE) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"user_name_cn"];        
    }
    
    //7@"联系人",
    if (infotype == INFO_TYPE_CONTACT) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"contact_name"];        
    }

    //8@"币种",
    if (infotype == INFO_TYPE_CURRENCY_TYPE) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"currency_name"];        
    }
    
    //9价格条款
    if (infotype == INFO_TYPE_PRICE_TERMS) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"dict_name_cn"];        
    }
    
    //10起运港
    if (infotype == INFO_TYPE_DEPARTURE_PORT) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"port_name_cn"];        
    }
    
    //11目的港
    if (infotype == INFO_TYPE_ARRIVAL_PORT) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"port_name_cn"];        
    }
    
    //12获取客户类型列表
    if (infotype == INFO_TYPE_CUSTOMER_TYPE) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"customer_type_name"];        
    }
    //13@"获取客户来源列表",
    if (infotype == INFO_TYPE_CUSTOMER_ORIGIN) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"dict_name_cn"];        
    }
    
    //14获取客户信用等级列表
    if (infotype == INFO_TYPE_CUSTOMER_CREADIT) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"creadit_level"];        
    }
    
    //15@"商机",
    if (infotype == INFO_TYPE_CHANCE) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"chance_name"];        
    }

    //16@"成本模型",
    if (infotype == INFO_TYPE_COST_MODEL) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"cost_model_name"];        
    }

    //17,报价单位
    if (infotype == INFO_TYPE_QUOT_PROD_UNIT) {        
        cell.textLabel.text =[tmp_dictionary objectForKey:@"unit_name_cn"];        
    }


    if ([lastSelectID length] > 0){
        if ([[tmp_dictionary objectForKey:@"id"] isEqualToString:lastSelectID]){
            cell.accessoryType=UITableViewCellAccessoryCheckmark;
            [cell setBackgroundColor:[UIColor clearColor]];
//            [cell setHighlighted:YES];
//            [cell setSelected:YES];
            self.lastIndexPath = indexPath;
        }
    }
    
    [tmp_dictionary release];

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{   
    int newRow = [indexPath row];
    int oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;
    
    NSMutableDictionary *tmp_dictionary = nil;
    if (newRow < [responseParams count])
    {
        tmp_dictionary = [[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:newRow]];
    }else
    {
        tmp_dictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    }
    
    NSString *p_id=[NSString stringWithString:[tmp_dictionary objectForKey:@"id"]];
    [tmp_dictionary release];
    
    if (newRow != oldRow)
    {
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        
        selectIndex = newRow;
        selectValue = newCell.textLabel.text;
        selectCode = p_id;
        
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath]; 
        oldCell.accessoryType = UITableViewCellAccessoryNone;
        [oldCell setHighlighted:NO];
        [oldCell setSelected:NO];

        self.lastIndexPath = indexPath;
    }
}

#pragma mark - 
#pragma mark - my function
- (void)doSearch{
    [super doSearch];
    //
    [self.table reloadData];
    
    [[[TaskManager Share] GetTaskByType:GetQuotSelectList Delegate:self] Excute];
    
}


-(void)AddArray
{
    [self.selectProductArray removeAllObjects];
    
    for(id key in indexpathDic)
    {
        NSMutableDictionary *dict = nil;//[[NSMutableDictionary alloc] initWithCapacity:0];
        dict=[indexpathDic objectForKey:key];

        [self.selectProductArray addObject:dict];
//        [dict release];
    }

    [self.navigationController popViewControllerAnimated:YES];
}

-(void)SetInfoType:(int)type
{
    infotype = type;
}

-(void)refreshData
{
     //设置标题
    //1@"产品类别"
    if (infotype == INFO_TYPE_PRODUCT_CATEGORY){
        self.title = INFO_STRING_PRODUCT_CATEGORY;
    }
    //2@"单位"
    if (infotype == INFO_TYPE_PRODUCT_UNIT){
        self.title = INFO_STRING_PRODUCT_UNIT;
    }
    //3@"海关编码"
    if (infotype == INFO_TYPE_PRODUCT_CUSTOM_CODE){
        self.title = INFO_STRING_PRODUCT_CUSTOM_CODE;
    }
    
    //4@"客户"
    if (infotype == INFO_TYPE_CUSTOMER){
        self.title = INFO_STRING_CUSTOMER;
    }
    //5产品
    if (infotype == INFO_TYPE_PRODUCT){
        self.title = INFO_STRING_PRODUCT;
    }
    
    //6@"业务员"
    if (infotype == INFO_TYPE_EMPLOYE){
        self.title =INFO_STRING_EMPLOYE;
    }
    
    //7@"联系人"
    if (infotype == INFO_TYPE_CONTACT){
        self.title =INFO_STRING_CONTACT;
    }
 
    //8@"币种"
    if (infotype == INFO_TYPE_CURRENCY_TYPE){
        self.title =INFO_STRING_CURRENCY;
    }
    //9@"价格条款"
    if (infotype == INFO_TYPE_PRICE_TERMS){
        self.title =INFO_STRING_PRICE_TERMS;
    }
    //10@"起运港"
    if (infotype == INFO_TYPE_DEPARTURE_PORT){
        self.title =INFO_STRING_DEPARTURE_PORT;
    }
    //11@"目的港"
    if (infotype == INFO_TYPE_ARRIVAL_PORT){
        self.title =INFO_STRING_ARRIVAL_PORT;
    }

    //12@"客户类型"
    if (infotype == INFO_TYPE_CUSTOMER_TYPE){
        self.title =INFO_STRING_CUSTOMER_TYPE;
    }
    //13@"客户来源"
    if (infotype == INFO_TYPE_CUSTOMER_ORIGIN){
        self.title =INFO_STRING_CUSTOMER_ORIGIN;
    }
    //14@"信用等级"
    if (infotype == INFO_TYPE_CUSTOMER_CREADIT){
        self.title =INFO_STRING_CUSTOMER_CREADIT;
    }

    //15@"商机",
    if (infotype == INFO_TYPE_CHANCE) {        
        self.title = INFO_STRING_CHANCE;
    }

    //16@"成本模型",
    if (infotype == INFO_TYPE_COST_MODEL) {        
        self.title = INFO_STRING_COST_MODEL;
    }

    //17,报价单位
    if (infotype == INFO_TYPE_QUOT_PROD_UNIT){
        self.title = INFO_STRING_QUOT_PROD_UNIT;
    }

    [[[TaskManager Share] GetTaskByType:GetQuotSelectList Delegate:self] Excute];
}

-(void) getMoreData
{
    [[[TaskManager Share] GetTaskByType:GetQuotSelectList Delegate:self] Excute];
}

-(void) OnPreExcute
{
    [super OnPreExcute];
}

-(void) DoInBackground
{
    if (getflag == NO && _isSearching == NO) {
        return;
    }
    startRow = [responseParams count];
    NSString *num = [NSString stringWithFormat:@"%i",startRow];
    NSString *rowsperpage = [NSString stringWithFormat:@"%i",PER_PAGE_ROWS];
    NSMutableArray *tmp=nil;
    XmlRpc *xml = [[XmlRpc alloc] init];
    
    switch (infotype) {
            
            //1产品类别
        case INFO_TYPE_PRODUCT_CATEGORY:
        {   
            if (_isSearching){
                tmp = [xml GetSearchProductCategoryList:p_search startRows:num rowsPerPage:rowsperpage];                
            }else{
                tmp = [xml GetProductCategoryList:num rowsPerPage:rowsperpage];
            }            
            break;
        }    
            
            //2品单位
        case INFO_TYPE_PRODUCT_UNIT:
        {   
            if (_isSearching){
                tmp = [xml GetSearchProductUnitList:p_search startRows:num rowsPerPage:rowsperpage];
            }else{
                tmp = [xml GetProductUnitList:num rowsPerPage:rowsperpage];
            }
            break;
        }    
            
            //3海关编码
        case INFO_TYPE_PRODUCT_CUSTOM_CODE:
        {   
            if (_isSearching){
                tmp = [xml GetSearchProductCustomsCodeList:p_search startRows:num rowsPerPage:rowsperpage];
            }else{
                tmp = [xml GetProductCustomsCodeList:num rowsPerPage:rowsperpage];
            }
            break;
        }   

        //4客户信息
        case INFO_TYPE_CUSTOMER:     
        {   
            if (_isSearching){
                tmp = [xml GetSearchCustomerList:[[Session share] getMemberID] PosiID:[[Session share] getMemberPosiID] Type:@"01" searchWord:p_search startRows:num rowsPerPage:rowsperpage];
            }else{
                tmp = [xml GetCustomerList:[[Session share] getMemberID] PosiID:[[Session share] getMemberPosiID] startRows:num rowsPerPage:rowsperpage];
            }
            break;
        }    
         
            //5产品信息
        case INFO_TYPE_PRODUCT:     
        {   
            if (_isSearching){
                tmp = [xml GetSearchProductList:[[Session share] getMemberID] searchCondition:p_search searchType:@"01" startRows:num rowsPerPage:rowsperpage];                
            }else{
                tmp = [xml GetProductList:[[Session share] getMemberID] startRows:num rowsPerPage:rowsperpage];
            }
            break;
        }    

            //6业务员
        case INFO_TYPE_EMPLOYE:     
        {   
            tmp = [xml getEmployeeList:[[Session share] getMemberPosiID]];
            break;
        }    
            
        //7联系人
        case INFO_TYPE_CONTACT:
        {
            if ([self.customerID length] >0){
                tmp = [xml GetCustContractList:self.customerID];
            }
            break;
        }
           
         //8@"币种"
        case INFO_TYPE_CURRENCY_TYPE:
        {   
            tmp = [xml GetCurrencyTypeList:num rowsPerPage:rowsperpage];
            break;
        }    
            
         //9@"价格条款"
        case INFO_TYPE_PRICE_TERMS:
        {   
            tmp = [xml GetPriceClauseTypeList:num rowsPerPage:rowsperpage];
            break;
        }    
        
        //10@"起运港"
        case INFO_TYPE_DEPARTURE_PORT:
        {   
            tmp = [xml GetPortList:num rowsPerPage:rowsperpage];
            break;
        }    
            
        //11@"目的港"
        case INFO_TYPE_ARRIVAL_PORT:
        {   
            tmp = [xml GetPortList:num rowsPerPage:rowsperpage];
            break;
        }    
            
            
         //12@"客户类型
        case INFO_TYPE_CUSTOMER_TYPE:
        {   
            tmp = [xml GetCustomerTypeList:num rowsPerPage:rowsperpage];
            break;
        }    
        
        //13客户来源，
        case INFO_TYPE_CUSTOMER_ORIGIN:
        {   
            tmp = [xml GetCustomerOriginList:num rowsPerPage:rowsperpage];
            break;
        }    
        
        //14信用等级，
        case INFO_TYPE_CUSTOMER_CREADIT:
        {   
            tmp = [xml GetCustomerCreditList:num rowsPerPage:rowsperpage];
            break;
        }    

        //15@"商机",
        case INFO_TYPE_CHANCE:
        {
            tmp = [xml GetChanceList:num rowsPerPage:rowsperpage];
            break;
        }

        //16,成本模型
        case INFO_TYPE_COST_MODEL:
        {
            tmp = [xml GetCostModelList:num rowsPerPage:rowsperpage];
            break;
        }
            
        //17,报价单位
        case INFO_TYPE_QUOT_PROD_UNIT:
        {
            tmp = [xml GetQuotProductUnitList:productID startRows:num rowsPerPage:rowsperpage];
            break;
        }
            
        default:
            break;
    }
    
    NSMutableArray *tmp_array=[[NSMutableArray alloc] initWithArray:tmp];
    for (NSMutableDictionary* itq in tmp_array) {
        [responseParams addObject:itq];
    }
    [tmp_array release];
    
    if ([tmp count]<PER_PAGE_ROWS) {
        getflag = NO;
    }

    [xml release];
    
    [self.table reloadData];
}

-(void) OnPostExcute
{
    [super OnPostExcute];
}

//- (IBAction)goBack:(id)sender
//{
//    if (self.selectBeginBlcok != nil) {
//        NSString *tmp_key=[NSString stringWithFormat:@"%d,%d",self.section,self.row];
//        if ([selectCode length]>0 && [selectValue length] >0)
//            self.selectBeginBlcok(selectValue,selectCode,tmp_key);
//    }
//    
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (IBAction)goBack
{
    if (self.selectBeginBlcok != nil) {
        NSString *tmp_key=[NSString stringWithFormat:@"%d,%d",self.section,self.row];
        if ([selectCode length]>0 && [selectValue length] >0)
            self.selectBeginBlcok(selectValue,selectCode,tmp_key);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
